package org.budo.support.mvcs;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author limingwei
 */
public class MvcsHandlerInterceptor implements HandlerInterceptor {
    public static final String HANDLER_IN_REQUEST_ATTRIBUTE_KEY = "org.budo.support.mvcs.Mvcs.HandlerInRequestAttributeKey";

    private static final ThreadLocal<HttpServletRequest> REQUEST_THREAD_LOCAL = new InheritableThreadLocal<HttpServletRequest>();

    private static final ThreadLocal<HttpServletResponse> RESPONSE_THREAD_LOCAL = new InheritableThreadLocal<HttpServletResponse>();

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        REQUEST_THREAD_LOCAL.set(request);
        RESPONSE_THREAD_LOCAL.set(response);

        request.setAttribute(HANDLER_IN_REQUEST_ATTRIBUTE_KEY, handler);
        return true;
    }

    public static HttpServletRequest getRequest() {
        return REQUEST_THREAD_LOCAL.get();
    }

    public static HttpServletResponse getResponse() {
        return RESPONSE_THREAD_LOCAL.get();
    }

    public static Object getHandler() {
        return Mvcs.getRequestAttribute(HANDLER_IN_REQUEST_ATTRIBUTE_KEY);
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {}

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        REQUEST_THREAD_LOCAL.remove();
        RESPONSE_THREAD_LOCAL.remove();
    }
}
